package com.daohang361.imqq.ui.trayIcon;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JFrame;

import com.csu.client.logger.EIMLogger;
import com.csu.client.module.vo.Cache;
import com.csu.client.tools.EIMClientConfig;
import com.csu.message.BaseMessage;
import com.csu.message.MessageType;
import com.csu.message.SysMessage;
import com.daohang361.imqq.resourse.ResourcesManagement;
import com.daohang361.imqq.ui.BaseFrame;
import com.daohang361.imqq.ui.EIMTalkFrame;
import com.daohang361.imqq.ui.ToolTip;

/**
 * 
 * 客户端的托盘组建 （ 单实例模式 ） 
 *      组成主要部件 1：收到消息列表 
 *                 2：QQ的主窗体 
 *             方法 1:依据信息改变托盘的图标
 *                 2：根据收到的信息打开聊天窗体
 */
public class EIMTrayIcon extends JFrame implements Runnable {

	private static final long serialVersionUID = 1L;

	private List<BaseMessage> reveMessageList; // 收到消息的列表

	private static EIMTrayIcon qqTrayIcon; // 单实例的控制量

	private int trayIconState; // 托盘图标的状态标志

	private TrayIcon trayIcon;

	private BaseFrame frame; // 与托盘一并的窗口

	private boolean isGetMsg = false; // 是否有消息

	private BaseMessage message; // 当前消息

	public boolean isGetMsg() {
		return isGetMsg;
	}

	public void setGetMsg(boolean isGetMsg) {
		this.isGetMsg = isGetMsg;
	}

	private EIMTrayIcon() {
		reveMessageList = new ArrayList<BaseMessage>();
		initEIMTrayIcon();
	}

	public static EIMTrayIcon getInStance() {
		if (qqTrayIcon == null) {
			qqTrayIcon = new EIMTrayIcon();
		}
		return qqTrayIcon;
	}

	public void run() {
	}

	/**
	 * 初始化托盘
	 */
	private void initEIMTrayIcon() {
		if (SystemTray.isSupported()) {
			SystemTray tray = SystemTray.getSystemTray();
//			Image image = initImage("ui/offline_TrayIcon.png");
			Image image = initImage("icon/12.png");
			PopupMenu popupMenu = initPopupMenu();
			trayIcon = new TrayIcon(image, "QQ:不死爬虫(365183440)\n声音:关闭\n消息提示框:关闭\n会话消息:任务栏头像闪动", popupMenu);

			trayIcon.addMouseListener(new java.awt.event.MouseAdapter() {
				public void mouseClicked(MouseEvent e) {
					if (e.getClickCount() == 2) {
						if (isGetMsg == true) {

							message = reveMessageList.remove(0);
							int msgType = message.getMsgType();

							switch (msgType) {

							case MessageType.TalkMessage_Type:
								Cache cahce=Cache.getInstance();
								EIMTalkFrame talkFrame = cahce.getTalkFrame(message.getSrcQQ());
								removeMessage(talkFrame.friend.getUserID());
								if (!talkFrame.isVisible()) {
									talkFrame.setVisible(true);
								}

								if (reveMessageList.size() > 0) {
									EIMLogger.INFO("信息列表的长度："
											+ reveMessageList.size());
									isGetMsg = true;
									message = reveMessageList.get(0);
									showIcon(message.getMsgType());
								} else {
									isGetMsg = false;
									showIcon(trayIconState);
								}
								break;

							case MessageType.SysMessage_Type:

								SysMessage msg = (SysMessage) message;
								processSysMessage(msg);
								if (reveMessageList.size() > 0) {
									EIMLogger.INFO("信息列表的长度："
											+ reveMessageList.size());
									isGetMsg = true;
									message = reveMessageList.get(0);
									showIcon(message.getMsgType());
								} else {
									isGetMsg = false;
									showIcon(trayIconState);
								}
								break;
							}
						} else {
							if (frame.isVisible()) {
								frame.setVisible(false);
							} else {
								frame.setVisible(true);
							}
						}

					}

				}
			});
			try {
				tray.add(trayIcon);
			} catch (AWTException e) {
				e.printStackTrace();
			}
		} else {
			EIMLogger.INFO("无法使用系统托盘!");
		}
	}

	/**
	 * 初始托盘的图标
	 * 
	 * @return
	 */
	public Image initImage(String name) {
		Image image = ResourcesManagement.getImageIcon(name, 16, 16).getImage();
		return image;
	}

	/**
	 * 初始托盘的一个弹出菜单
	 * 
	 * @return 弹出菜单
	 */
	private PopupMenu initPopupMenu() {
		PopupMenu popup = new PopupMenu();
		MenuItem exitItem=null;
		try {
			MenuItem resetuser_Menu = new MenuItem("\u66F4\u6539\u72B6\u6001");//更改状态
			exitItem = new MenuItem("exit");
			MenuItem systemConfig = new MenuItem("设置");
			MenuItem systemTools = new MenuItem("工具");
			popup.add(resetuser_Menu);
			popup.add(systemConfig);
			popup.add(systemTools);
			popup.add(exitItem);
		} catch (Exception e) {
			// TODO: handle exception
		}
		exitItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					System.exit(0);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
		return popup;
	}

	/**
	 * 根据不同的情况显示不同德托盘图标
	 * 
	 * @param flag
	 *            ：情况参数
	 * 
	 * 具体如下 11111110: 上线 11111111: 下线，离开 11111112: 登录 11111113: 隐身
	 * 
	 * MessageType.SysMessage_Type: 收到系统消息
	 * MessageType.TalkMessage_Type: 收到个人消息
	 * MessageType.TeamMessage_Type:收到群消息
	 * 
	 */
	public void showIcon(int flag) {
		if (EIMClientConfig.OnlineTryIcon_Type == flag) {
			showOnlineIco();
		} else if (EIMClientConfig.OffLineTryIcon_Type == flag) {
			showOfflineIco();
		} else if (EIMClientConfig.LoginingTryIcon_Type == flag) {
			showDengluIco();
		} else if (EIMClientConfig.YinShengTryIcon_Type == flag) {
			showYinshenIco();
		} else if (MessageType.SysMessage_Type == flag) {
			showsYsMessageIco();
		} else if (MessageType.TalkMessage_Type == flag) {
			showPopMessageIco();
		} else if (MessageType.TeamMessage_Type == flag) {
			showTeamMessageIco();
		}
	}

	/**
	 * 显示在线图标
	 * 
	 */
	private void showOnlineIco() {
//		Image image = ResourcesManagement.getImage("ui/online_TrayIcon.png", 16, 16);
		Image image = initImage("ui/01.png");
		trayIcon.setImage(image);
	}

	/**
	 * 显示下线图标
	 * 
	 */
	private void showOfflineIco() {
//		Image image = initImage("ui/offline_TrayIcon.png");
		Image image = initImage("ui/01.png");
		trayIcon.setImage(image);
	}

	/**
	 * 显示正在登陆时的图标
	 * 
	 */
	private void showDengluIco() {
		Image image = ResourcesManagement.getImage("ui/mydong.gif", 16, 16);
		trayIcon.setImage(image);
	}

	/**
	 * 显示隐身时的图标
	 * 
	 */
	private void showYinshenIco() {
		Image image = initImage("ui/yinshen.png");
		trayIcon.setImage(image);

	}

	/**
	 * 显示收到系统信息时的图标
	 * 
	 */
	private void showsYsMessageIco() {
		Image image = ResourcesManagement.getImage("ui/sysMsg.gif", 16, 16);
		trayIcon.setImage(image);
	}

	/**
	 * 显示收到好友聊天信息时的图标
	 * 
	 */
	private void showPopMessageIco() {
//		Image image = ResourcesManagement.getImage("ui/popMsg.gif", 16, 16);
		Image image = ResourcesManagement.getImage("icon/01.ico", 16, 16);
		trayIcon.setImage(image);
	}

	/**
	 * 显示收到群聊天信息时的图标
	 * 
	 */
	private void showTeamMessageIco() {
		Image image = ResourcesManagement.getImage("ui/teamMsg.gif", 16, 16);
		trayIcon.setImage(image);
	}

	/**
	 * 把接收到得信息加入到信息列表中
	 * 
	 * @param messge
	 *            :接收到得信息
	 */
	public void addRevedMessage(BaseMessage messge) {
		reveMessageList.add(messge);
	}

	/**
	 * 根据消息的发送者QQ把他的留言消息从留言列表中删除
	 * 
	 * @param srcQQ
	 */
	private void removeMessage(String srcQQ) {

		List<BaseMessage> msgList = new ArrayList<BaseMessage>();
		for (int i = 0; i < reveMessageList.size(); i++) {
			BaseMessage message = reveMessageList.get(i);
			if (srcQQ.equals(message.getSrcQQ())) {
				msgList.add(message);
			}
		}
		if (msgList.size() > 0) {
			for (int r = 0; r < msgList.size(); r++) {
				reveMessageList.remove(msgList.get(r));
			}
		}

	}
	
	private void processSysMessage(SysMessage sysMsg){
		int msgContentType=sysMsg.getMsgContentType();
		String srcQQ=message.getSrcQQ();
		
    	SimpleDateFormat  sf   =new SimpleDateFormat("HH:mm:ss");//这里的格式自己按需要写   
		Date d=new Date();   
		String dataString   = sf.format(d);
		Cache cache=Cache.getInstance();
		switch(msgContentType){
		 case MessageType.SysMessage_Online:
			 String name1=cache.getfriendMap().get(srcQQ).getUserName();
			 final String msg1="时间"+dataString+"：\r\n 你的好友："+name1+"上线了！";
			 java.awt.EventQueue.invokeLater(new Runnable() {
					public void run() {
						ToolTip.startToolTip(msg1);
					}
				});
			 break;
		 case MessageType.SysMessage_Exit:
			 String name2=cache.getfriendMap().get(srcQQ).getUserName();
			 final String msg2="时间"+dataString+"：\r\n 你的好友："+name2+"下线了！";
			 java.awt.EventQueue.invokeLater(new Runnable() {
					public void run() {
						ToolTip.startToolTip(msg2);
					}
				});
			 break;
		 case MessageType.SysMessage_News:
			 final String sysMsgConten=sysMsg.getSysMsg();
			 java.awt.EventQueue.invokeLater(new Runnable() {
					public void run() {
						ToolTip.startToolTip(sysMsgConten);
					}
				});
			 break;
		}
	}

	/**
	 * 根据收到消息的srcQQ参数来得到聊天框
	 * 
	 * @param srcQQ
	 */
	@SuppressWarnings("unused")
	private void getQQtalkFrameBySrcQQ(String srcQQ) {

	}
	public List<BaseMessage> getReveMessageList() {
		return reveMessageList;
	}

	public void setReveMessageList(List<BaseMessage> reveMessageList) {
		this.reveMessageList = reveMessageList;
	}

	public BaseFrame getFrame() {
		return frame;
	}

	public void setFrame(BaseFrame frame) {
		this.frame = frame;
	}

	public int getTrayIconState() {
		return trayIconState;
	}

	public void setTrayIconState(int trayIconState) {
		this.trayIconState = trayIconState;
	}

}
